const Router = require("koa-router");

const { auth } = require("../middleware/auth.middleware");
const { validatorParams } = require("../middleware/general.middleware");
const { verifyGoodsId, verifyCartId } = require("../middleware/cart.middleware");
const { add, findAll, update, remove, batchSelected, total } = require("../controller/cart.controller");
const { cartFormatError } = require("../constant/error.type");

// 实例化子路由对象
const router = new Router({ prefix: "/cart" });

/**
 * 添加商品到购物车接口
 * 实际的路由路径：/carts/
 * 当用户请求命中当前路由时，请求交先由auth中间件验证用户是否已经登陆了，如果验证登陆了就交由 validatorParams 中间件进行校验参数格式，格式校验通过再交由 verifyGoodsId 校验商品是否存在，商品存在再交给controller处理
 */
router.post("/", auth, validatorParams({ goods_id: "number" }, cartFormatError), verifyGoodsId, add);

/**
 * 获取购物车列表接口
 */
router.get("/", auth, findAll);

/**
 * 更新购物车接口
 */
router.patch(
  "/:id",
  auth,
  validatorParams(
    {
      number: { type: "number", required: false },
      selected: { type: "bool", required: false },
    },
    cartFormatError,
  ),
  verifyCartId,
  update,
);

/**
 * 删除购物车接口（支持单个或批量删除）
 */
router.delete("/", auth, validatorParams({ ids: "array" }, cartFormatError), remove);

/**
 * 批量更新购物车的选中状态接口（购物车全选 | 购物车全不选）
 */
router.post("/batchSelected", auth, validatorParams({ selected: "bool" }, cartFormatError), batchSelected);

/**
 * 查询购物车总数接口
 */
router.get("/total", auth, total);

module.exports = router;
